package com.nuo.common.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;



@Slf4j
public class RichTextUtil {


    /**
     *
     * @param text 富文本内容
     * @return  返回处理图片后的数据
     */
    public  String richText(String text) throws IOException {
        String s=text;
        String result=text;//返回结果
        List<String> imgStr = ImgBaseUtil.getImgStr(s); //每组base64编码图片
        if (imgStr.isEmpty()){
            return text;
        }
        for (String s1:imgStr){
            // 不是base64编码的不要转换了直接跳过
            if (!s1.contains("data:image")) continue;
            //每个base64转换并上传
            MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(s1);
            File file = new File(multipartFile.getName());
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);

            HttpResponse execute = HttpRequest.post("http://124.223.79.4:13333/storage/local/uploadByPathName")
                    .form("pathName", "baseToImg")
                    .form("fileArr", file)
                    .execute();

            log.info(execute.body());
            String body = execute.body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONObject body1 = JSONObject.parseObject(jsonObject.get("body").toString());
            JSONArray jsonArray = JSONObject.parseArray(body1.get("dataList").toString());
            JSONObject jsonObject1 = JSONObject.parseObject(jsonArray.get(0).toString());

            file.delete();
            String foreverUrl=jsonObject1.get("fileUrl").toString();
            if (Objects.isNull(result)){
                result=s.replace(s1,foreverUrl); //第一次替换
            }
            result=result.replace(s1,foreverUrl); //前边替换过，继续替换

        }
        return result;
    }

}

